<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" clearable auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" clearable auto-complete="off" placeholder="密码"
          @keyup.enter.native="handleLogin">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <div class="caCode" v-if="captchaEnabled">
        <el-input ref="username" v-model="userInput" placeholder="请输入验证码" name="username" type="text" tabindex="1" autocomplete="on"
          clearable />
        <canvas ref="canvas" @click="createCode" width="140" height="60"></canvas>
      </div>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
          @click.native.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: process.env.NODE_ENV=='production'?true:false,
      // 注册开关
      register: false,
      otherQuery: {},
      redirect: undefined,
      code: '', // 验证码字符串
      userInput: '' // 用户输入的验证码
    };
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  mounted() {
    if(this.captchaEnabled){

      this.createCode()
    }
  },
  methods: {
    // 生成验证码
    createCode() {
      const that = this;
      let codeLength = 4; // 验证码长度
      let canvas = this.$refs.canvas;
      let ctx = canvas.getContext('2d');
      let codeChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      let code = '';
      for (let i = 0; i < codeLength; i++) {
        let charIndex = Math.floor(Math.random() * codeChars.length);
        code += codeChars.charAt(charIndex);
      }
      this.code = code;

      // 绘制验证码图片
      ctx.fillStyle = that.MathColor(180, 230);
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.font = that.MathNumber(30, 40) + 'px Arial';
      ctx.fillStyle = that.MathColor(80, 180);
      ctx.fillText(code, 20, 45);
      for (var i = 0; i < 6; i++) {
        ctx.strokeStyle = that.MathColor(0, 255);
        ctx.beginPath();
        ctx.moveTo(that.MathNumber(0, canvas.width), that.MathNumber(0, canvas.height));
        ctx.lineTo(that.MathNumber(0, canvas.width), that.MathNumber(0, canvas.height));
        ctx.stroke();
      }
      for (var i = 0; i < 50; i++) {
        ctx.fillStyle = that.MathColor(0, 255);
        ctx.beginPath();
        ctx.arc(that.MathNumber(0, canvas.width), that.MathNumber(0, canvas.height), 0.5, 0, 2 * Math.PI);
        ctx.fill();
      }
    },
    //随机整数
    MathNumber(min, max) {
      var n = Math.floor(Math.random() * (max - min) + min);
      return n;
    },
    //随机颜色
    MathColor(min, max) {
      var r = this.MathNumber(min, max);
      var g = this.MathNumber(min, max);
      var b = this.MathNumber(min, max);
      return `rgb(${r},${g},${b})`;
    },
    getCode() {
      this.codeUrl = null
      setTimeout(() => {
        this.codeUrl = '/api/user/captcha?timestamp=' + new Date().getTime()
      })
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
      };
    },
    handleLogin() {
      if (this.captchaEnabled) {
        if (this.userInput.toLowerCase() !== this.code.toLowerCase()) {
          this.$message.error('验证码错误，请重新输入');
          this.createCode();
          this.userInput = ''
          return false
        }
      }
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store.dispatch("Login", this.loginForm).then(() => {
            Cookies.set('username',this.loginForm.username)
            Cookies.set('password',encrypt(this.loginForm.password))
            
            this.$router.push({ path: this.redirect || "/" }).catch(() => { });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: 100% 100%;
}

.title {
  margin: 0px auto 10px auto;
  text-align: center;
  color: #fff;

  &h3 {
    margin-bottom: 10px;
  }
}

.login-form {
  border-radius: 6px;
  // background: #ffffff;
  backdrop-filter: blur(20px);
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 30%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.caCode {
  display: flex;
  height: 40px;
  border: 1px solid rgba(0, 0, 0, 0);
  overflow: hidden;
  border-radius: 5px;
  color: #333;
  margin-bottom: 22px;

  el-input {
    width: 60%;
  }
}
</style>
